var ruta;
var bus = null;
var posicTempBusy = new Array();
var posicTempReserved = new Array();
var flag= 0;
function initbus(){
    bus=[[0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0]];

    var grupo=document.getElementById('hourform').hourgroup1;
    var values = radiovalue(grupo);
    ruta = values

    var argsArray=new Array();
    //window.alert(ruta);
    argsArray.push(newArg("action","loadbusyplace"));
    argsArray.push(newArg("ID",ruta));
    argsArray.join("&");
    sendRequest("../controller/controllerSale.jsp",argsArray,linkChosePlace_onclick_response);
}

function linkChosePlace_onclick_response(){
    if (isValidResponse(this))
    {
        var res=this.responseText;
        if(res!=""){
            var info=eval("("+res+")");

            for(i=0; i<info.data.length; i++){
                if(info.data[i].state == "Vendido")
                    posicTempBusy.push(info.data[i].busyplace)
                else
                    posicTempReserved.push(info.data[i].busyplace)
            }
        }else
            window.alert("Not Found!!");
    }
    var elem;
     for(i=0; i<=30; i++){
         for(j=0;j<posicTempBusy.length;j++){
             if(i == posicTempBusy[j]){
                 elem = document.getElementById(i)
                 elem.className = "AGV_SillaOcupada"
             }else if(i == posicTempReserved[j]){
                 elem = document.getElementById(i)
                 elem.className = "AGV_SillaReservada"
             }

         }
     }
}

function canSelectPlace(aCell){
    var elem;
    elem = document.getElementById(aCell);
    if(flag == 0){
        if(elem.className=="AGV_SillaOcupada"){
            alert("El puesto elegido se encuentra ocupado");
        }else if(elem.className=="AGV_SillaLibre" && flag!=1){
            elem.className = "AGV_SillaSeleccionada";
            document.getElementById('txtPlace').value = aCell;
            flag = 1;
            //$.fancybox.close();
        }else if(elem.className=="AGV_SillaReservada"){
            alert("El puesto elegido se encuentra reservado");
        }
    }else{
        if(elem.className=="AGV_SillaSeleccionada"){
            elem.className="AGV_SillaLibre"
            flag = 0;
        }
    }
}


function loadSource(){
    var argsArray=new Array();
    argsArray.push(newArg("action","seek"));
    sendRequest("../controller/controllerSale.jsp",argsArray,show);
}


function changeDestination(){
    var argsArray=new Array();
    argsArray.push(newArg("action","changed"));
    var i = document.getElementById("selSource").selectedIndex;
    var txtCitySource = document.getElementById("selSource").options[i].text;
    argsArray.push(newArg("ID",txtCitySource));
    argsArray.join("&");
    sendRequest("../controller/controllerSale.jsp",argsArray,showChangeDestination);
}

function button_btnAgree(){
        var place = document.getElementById("txtPlaceSelected").value;
        var date = document.getElementById("txtDateTravel").value;
        var route = ruta;
        var user = document.getElementById("txtUserID").value;
        //window.alert(date + " - " + place + " - " + route + " - " + user);
    if(document.getElementById('txtAction').value == "sell"){
        
        if(date!="" && place!=""){
            var argsArray=new Array();
            argsArray.push(newArg("action","addticket"));
            //argsArray.push(newArg("varType",type));
            argsArray.push(newArg("varPlace",place));
            argsArray.push(newArg("varDate",date));
            argsArray.push(newArg("varRoute",route));
            argsArray.push(newArg("varUser",user));
            argsArray.join("&");
            sendRequest("../controller/controllerSale.jsp",argsArray,addingticket);
        }
    }else if(document.getElementById('txtAction').value == "delete"){
        var html = 'ID del Ticket: <input type="text" id="txtTicketID">'+
        '<input type="button" value="Confirmar" id="btnDeleteAgree" onclick="deleteTicket()"/>'
        document.getElementById('lisHours').innerHTML = html
        document.getElementById('place').className = "placeHidden";
    }else if(document.getElementById('txtAction').value == "reserve"){
        if(date!="" && route!="" && place!=""){
            var argsArray2 = new Array();
            argsArray2.push(newArg("action","reserveticket"));
            //argsArray.push(newArg("varType",type));
            argsArray2.push(newArg("varPlace",place));
            argsArray2.push(newArg("varDate",date));
            argsArray2.push(newArg("varRoute",route));
            argsArray2.push(newArg("varUser",user));
            argsArray2.join("&");
            sendRequest("../controller/controllerSale.jsp",argsArray2,btnAgree_onclick_response);
        }
    }else
        window.alert("none");

}

function btnAgree_onclick_response(){
    if (isValidResponse(this))
    {
        var res=this.responseText;

        if(res!=""){

        //window.alert(res);
            var info=eval("("+res+")");

            for(var i=0; i<info.data.length; i++){
                if(info.data[i].ticketID!="")
                    window.alert(info.data[i].ticketID)
            }
        }else
            window.alert("Not Found!!");
    }
}

function btnDelete_onclick(){
    var html = 'ID del Ticket: <input type="text" id="txtTicketID">'+
        '<input type="button" value="Confirmar" id="btnDeleteAgree" onclick="deleteTicket()"/>'
    document.getElementById('lisHours').innerHTML = html
    document.getElementById('place').className = "placeHidden";
}

function deleteTicket(){
    var argsArray=new Array();
    argsArray.push(newArg("action","deleteticket"));
    var id = document.getElementById("txtTicketID1").value;
    argsArray.push(newArg("ID",id));
    argsArray.join("&");
    sendRequest("../controller/controllerSale.jsp",argsArray,btnDeleteAgree_onclick_response);
}

function btnDeleteAgree_onclick_response(){
    window.alert("registro eliminado")
}

function radiovalue(radios) {
    for (i = 0; radio = radios[i]; i++) {
       // window.alert(radio.value)
        if (radio.checked) {
           return radio.value;
        }
    }
    return -1

}


function show()
{
    var html = '</br>';
    if (isValidResponse(this))
    {
        var res=this.responseText;
        
        if(res!=""){

        //window.alert(res);
            var info=eval("("+res+")");
           
            for(var i=0; i<info.data.length; i++){
                html+='<option>';
                html+=info.data[i].nameCity+'</option>';
            }
            document.getElementById('selSource').innerHTML = html;
        }else
            window.alert("Not Found!!");
    }
}

function showChangeDestination(){
    var html ='</br>';
    if(isValidResponse(this)){
        
        var res = this.responseText;
        //window.alert(res);
        if(res!=""){
            var info = eval("("+res+")");

            for(var i=0; i<info.data.length; i++){
                html +='<option>';
                html +=info.data[i].nameCityD+'</option>';
            }
            document.getElementById('selDestination').innerHTML = html;
        }else
            window.alert("Not found destination!!");
        
    }
}
function seePlaces(){
    window.alert("Pressed see");
    
}
function addingticket(){
    var result;
    if(isValidResponse(this)){
        var res = this.responseText;
        if(res!=""){
            var info = eval("("+res+")");
            for(i=0; i<info.data.length; i++){
                result = info.data[i].result;
                if(result == "0"){
                   window.alert("Ingreso Satisfactorio" )
                       //+ "No Ticket"+ info.data[i].ticketnum)
                }
            }
        }else{
                window.alert("Error al ingreso de los datos")
        }
    }
       //window.alert(result);

}


function btnReserve_onclick(){
    var html='<form id="hourform"><table class="board" align="center"><tr><td></td><td align="center">Hora de Salida</td><td align="center">Tarifa</td><td align="center">Puestos Disponibles</td></tr>';
    if (isValidResponse(this))
    {
        var res=this.responseText;
        if(res!=""){
           var info=eval("("+res+")");
            for(i=0; i<info.data.length; i++){
           html+='<tr> <td width="20px"><input type="radio" name="hourgroup1" id="radio'+info.data[i].idRoute+'" value="'+info.data[i].idRoute+'"></td>'
           html+='<td> <input type="text" id="exitRoute'+info.data[i].idRoute+'" value="'+info.data[i].exitRoute+'" onkeypress="return validaNombYApe(event)"></td>'
           html+='<td> <input type="text" id="costRoute'+info.data[i].idRoute+'" value="'+info.data[i].costRoute+'" onkeypress="return validaNombYApe(event)"></td>'
            }
            html+='</tr></table></form>'
            document.getElementById('place').className = "placeVisible";
            document.getElementById('lisHours').innerHTML = html
        }else
            window.alert("Not Found!!");
    }
}
function btnNextReserve_onclick(){
    //window.alert(document.getElementById('txtAction').value)
    if(document.getElementById('txtAction').value == "reserve"){
        var grupo=document.getElementById('hourform').hourgroup1;
        var values = radiovalue(grupo);
        ruta = values
       // window.alert(ruta);

        if(values != -1){

            var txtHourV=document.getElementById("exitRoute"+values).value;
            var txtPlaceV=document.getElementById("txtPlace").value;
            var txtCostV=document.getElementById("costRoute"+values).value;

        html='<table class="board" align="center"><tr>'+
                        '<td colspan="2">Hora de Salida</td>'+
                        '<td><input type="text" readonly="true" id="txtHourSelected" value="'+txtHourV+'"></td>'+
                    '</tr><tr><td colspan="2">Puesto</td>'+
                        '<td><input type="text" readonly="true" id="txtPlaceSelected" value="'+txtPlaceV+'"></td>'+
                    '</tr><tr><td>Tarifa</td>'+
                        '<td><input type="text" readonly="true" id="txtCostSelected" value="'+txtCostV+'"></td>'+
                        '<td><input type="button"  id="btnAgree" value="Confirmar" onclick="button_btnAgree()"></td>'+
                    '</tr></table>'
        document.getElementById('place').className = "placeHidden";
        document.getElementById('lisHours').innerHTML = html
        }
    }else
        window.alert("none")
}

function seeSell(){
    var html='<form id="hourform"><table class="board" align="center"><tr><td></td><td align="center">Hora de Salida</td><td align="center">Tarifa</td><td align="center">Puestos Disponibles</td></tr>';
    if (isValidResponse(this))
    {
        var res=this.responseText;
        if(res!=""){
           var info=eval("("+res+")");
            for(i=0; i<info.data.length; i++){
           html+='<tr> <td width="20px"><input type="radio" name="hourgroup1" id="radio'+info.data[i].idRoute+'" value="'+info.data[i].idRoute+'"></td>'
           html+='<td> <input type="text" id="exitRoute'+info.data[i].idRoute+'" value="'+info.data[i].exitRoute+'" onkeypress="return validaNombYApe(event)"></td>'
           html+='<td> <input type="text" id="costRoute'+info.data[i].idRoute+'" value="'+info.data[i].costRoute+'" onkeypress="return validaNombYApe(event)"></td>'
            }
            html+='</tr></table></form>'
            document.getElementById('place').className = "placeVisible";
            document.getElementById('lisHours').innerHTML = html
        }else
            window.alert("Not Found!!");
    }
}

function btnCancelUpdate_onclick_response(){
     if(isValidResponse(this)){
        var res=this.responseText;
        if(res!=""){
           var info=eval("("+res+")")
           
               window.alert("Modificación Exitosa"+info.data.result[0]);
           
        }
    }else
        window.alert("problemas")
}

function btnNextDelete_onclick(){
    //window.alert(document.getElementById('txtAction').value)
    if(document.getElementById('txtAction').value == "sell"){
        var grupo=document.getElementById('hourform').hourgroup1;
        var values = radiovalue(grupo);
        ruta = values
       // window.alert(ruta);

        if(values != -1){

            var txtHourV=document.getElementById("exitRoute"+values).value;
            var txtPlaceV=document.getElementById("txtPlace").value;
            var txtCostV=document.getElementById("costRoute"+values).value;

        html='<table class="board" align="center"><tr>'+
                        '<td colspan="2">Hora de Salida</td>'+
                        '<td><input type="text" readonly="true" id="txtHourSelected" value="'+txtHourV+'"></td>'+
                    '</tr><tr><td colspan="2">Puesto</td>'+
                        '<td><input type="text" readonly="true" id="txtPlaceSelected" value="'+txtPlaceV+'"></td>'+
                    '</tr><tr><td>Tarifa</td>'+
                        '<td><input type="text" readonly="true" id="txtCostSelected" value="'+txtCostV+'"></td>'+
                        '<td><input type="button"  id="btnAgree" value="Confirmar" onclick="button_btnAgree()"></td>'+
                    '</tr></table>'
        document.getElementById('place').className = "placeHidden";
        document.getElementById('lisHours').innerHTML = html
        }
    }else if(document.getElementById('txtAction').value == "delete"){
        var argsArray=new Array();
        argsArray.push(newArg("action","deleteticket"));
        var id = document.getElementById("txtTicketID1").value;
        argsArray.push(newArg("ID",id));
        argsArray.join("&");
        sendRequest("../controller/controllerSale.jsp",argsArray,btnDeleteAgree_onclick_response);
    }else
        window.alert("none")
}
function btnQueryReserve_onclick_response(){
    var html='<table class="board" align="center"><tr><td colspan="2" align="center">INFORMACIÓN DEL TICKET</td></tr>';
    if (isValidResponse(this))
    {
        var res=this.responseText;
        if(res!=""){
            var info=eval("("+res+")");
            for(i=0; i<info.data.length; i++){
                html+='<tr><td>Usuario</td><td><input type="text" id="txtticketuser" readonly="true" value="'+info.data[i].ticketuser+'"></td></tr>'
                html+='<tr><td>Va desde</td><td><input type="text" id="txtticketsource" readonly="true" value="'+info.data[i].ticketsource+'"></td></tr>'
                html+='<tr><td>Hasta</td><td><input type="text" id="txtticketdestination" readonly="true" value="'+info.data[i].ticketdestination+'"></td></tr>'
                html+='<tr><td>Hora de Salida</td><td><input type="text" id="txttickethour" readonly="true" value="'+info.data[i].tickethour+'"></td></tr>'
                html+='<tr><td>Fecha Salida</td><td><input type="text" class="hasDatepicker" id="txtticketdate" value="'+info.data[i].ticketdate+'"></td></tr>'
                html+='<tr><td>Estado del ticket</td><td><input type="text"  id="txttickettype" value="'+info.data[i].tickettype+'"></td></tr>'
                html+='<tr><td>Puesto</td><td><input type="text"  id="txtticketplace" value="'+info.data[i].ticketplace+'"></td></tr>'
                
            }
            html+='</table>'
            document.getElementById('place').className = "placeHidden";
            document.getElementById('lisHours').innerHTML = html
    }else
       window.alert("Not Found!!");
    }
}

function btnQuery_onclick_response(){
    var html='<table class="board" align="center"><tr><td colspan="2" align="center">INFORMACIÓN DEL TICKET</td></tr>';
    if (isValidResponse(this))
    {
        var res=this.responseText;
        if(res!=""){
            var info=eval("("+res+")");
            for(i=0; i<info.data.length; i++){
                html+='<tr><td>Usuario</td><td><input type="text" id="txtticketuser" readonly="true" value="'+info.data[i].ticketuser+'"></td></tr>'
                html+='<tr><td>Va desde</td><td><input type="text" id="txtticketsource" readonly="true" value="'+info.data[i].ticketsource+'"></td></tr>'
                html+='<tr><td>Hasta</td><td><input type="text" id="txtticketdestination" readonly="true" value="'+info.data[i].ticketdestination+'"></td></tr>'
                html+='<tr><td>Hora de Salida</td><td><input type="text" id="txttickethour" readonly="true" value="'+info.data[i].tickethour+'"></td></tr>'
                html+='<tr><td>Fecha Salida</td><td><input type="text" class="hasDatepicker" id="txtticketdate" value="'+info.data[i].ticketdate+'"></td></tr>'
                html+='<tr><td>Estado del Ticket</td><td><input type="text"  id="txttickettype" value="'+info.data[i].tickettype+'"></td></tr>'
                document.getElementById('txtPlace').value = info.data[i].ticketplace
            }
            html+='</table>'
            document.getElementById('place').className = "placeVisible";
            document.getElementById('lisHours').innerHTML = html
    }else
       window.alert("Not Found!!");
    }
}

$(document).ready(function()
{
    $("#btnQuery").click(function(){
        $("#txtAction").val("delete");
        $("#btnNext").val("Eliminar");
        $("#btnCancelUpdate").val("Modificar");
        var ticketId = $("#txtTicketID1").val();
       
        if(ticketId!=""){
            var argsArray=new Array();
            argsArray.push(newArg("action","seeTicketData"));
            argsArray.push(newArg("ID",ticketId));
            argsArray.join("&");
            sendRequest("../controller/controllerSale.jsp",argsArray,btnQuery_onclick_response);
          //  alert(source + " - " + destination + " - " + date);
        }else
           alert('No ha digitado ningun id de tickete', 'Error', 'Error Dialog');
    });
    $("#btnQueryReserve").click(function(){
        //$("#txtAction").val("delete");
        //$("#btnNext").val("Eliminar");
        //$("#btnCancelUpdate").val("Modificar");
        var ticketId = $("#txtTicketID1").val();

        if(ticketId!=""){
            var argsArray=new Array();
            argsArray.push(newArg("action","seeTicketData"));
            argsArray.push(newArg("ID",ticketId));
            argsArray.join("&");
            sendRequest("../controller/controllerSale.jsp",argsArray,btnQueryReserve_onclick_response);
          //  alert(source + " - " + destination + " - " + date);
        }else
           alert('No ha digitado ningun id de tickete', 'Error', 'Error Dialog');
    });
    
    $("#btnSell").click(function(){
        $("#txtAction").val("sell");
        $("#btnNext").val("Continuar");
        $("#btnCancelUpdate").val("Cancelar");
        var user = $("#txtUserID").val();
        var source = $("#selSource").val();
        var destination = $("#selDestination").val();
        var date = $("#txtDateTravel").val();
        //alert($("#txtUserID").val());
        //alert(source + " - " + destination + " - " + date + " - " + user);
        if(destination!="Seleccione" ){
            var argsArray=new Array();
            argsArray.push(newArg("action","seehours"));
            argsArray.push(newArg("txtUserID",user));
            argsArray.push(newArg("txtsource",source));
            argsArray.push(newArg("txtdestination",destination));
            argsArray.join("&");
            sendRequest("../controller/controllerSale.jsp",argsArray,seeSell);         
        }else
           alert('No ha seleccionado ninguna ciudad destino', 'Error', 'Error Dialog');

    });

    $("#btnCancelUpdate").click(function()
    {
        if($("#btnCancelUpdate").val()=="Cancelar")
        {
            document.getElementById('place').className = "placeHidden";
            document.getElementById('lisHours').innerHTML = '';
            document.getElementById('txtPlace').value = "";
        }else if($("#btnCancelUpdate").val()=="Modificar")
        {
            var ticketID = $("#txtTicketID1").val();
            var tickettype = $("#tickettype").val();
            var ticketplace = $("#txtPlace").val();
            var date = $("#txtticketdate").val();
            //alert($("#txtUserID").val());
            //alert(source + " - " + destination + " - " + date + " - " + user);
            if((ticketID!="") && (tickettype!="") && (ticketplace!="")&& (date!="")){
                var argsArray=new Array();
                argsArray.push(newArg("action","updateticket"));
                argsArray.push(newArg("ticketID",ticketID));
                argsArray.push(newArg("tickettype",tickettype));
                argsArray.push(newArg("ticketplace",ticketplace));
                argsArray.push(newArg("date",date));
                argsArray.join("&");
                sendRequest("../controller/controllerSale.jsp",argsArray,btnCancelUpdate_onclick_response);
            }
        }
    });

    $("#btnReserve").click(function(){
        $("#txtAction").val("reserve");
        $("#btnNext").val("Continuar");
        $("#btnCancelUpdate").val("Cancelar");
        var user = $("#txtUserID").val();
        var source = $("#selSource").val();
        var destination = $("#selDestination").val();
        var date = $("#txtDateTravel").val();
        //alert($("#txtUserID").val());
        //alert(source + " - " + destination + " - " + date + " - " + user);
        if(destination!="Seleccione" ){
            var argsArray=new Array();
            argsArray.push(newArg("action","seehours"));
            argsArray.push(newArg("txtUserID",user));
            argsArray.push(newArg("txtsource",source));
            argsArray.push(newArg("txtdestination",destination));
            argsArray.join("&");
            sendRequest("../controller/controllerSale.jsp",argsArray,btnReserve_onclick);
        }else
           alert('No ha seleccionado ninguna ciudad destino', 'Error', 'Error Dialog');

    });
});